package com.wqj.kyee.gps.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.wqj.kyee.gps.R;
import com.wqj.kyee.gps.custom.MyAxisValueFormatter;
import com.wqj.kyee.gps.custom.SVAxisValueFormatter;
import com.wqj.kyee.gps.nmea.NMEA;
import com.wqj.kyee.gps.service.NMEAParserService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SatelliteCN0Activity extends AppCompatActivity  implements OnChartValueSelectedListener, NMEAParserService.OnInfoUpdateListener{

    private static final String TAG = SatelliteCN0Activity.class.getSimpleName();

    private Typeface mTfRegular;
    private Typeface mTfLight;

    private HorizontalBarChart mChart;
    SVAxisValueFormatter xAisFormatter;

    private boolean needRefreshData = false;


    private Boolean isServiceBond = false;
    private NMEAParserService mNMEAParserService;
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            Log.e(TAG, "onServiceConnected");
            mNMEAParserService = ((NMEAParserService.LocalBinder) service).getService();
            if (mNMEAParserService != null) {
                mNMEAParserService.setOnInfoUpdateListener(SatelliteCN0Activity.this);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "onServiceDisconnected");
            mNMEAParserService = null;
        }
    };

    private Toolbar mToolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_satellite_cn0);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        mToolbar.setNavigationIcon(R.drawable.back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");

        mChart = (HorizontalBarChart) findViewById(R.id.id_horizontalBarChart);
        mChart.setOnChartValueSelectedListener(this);

        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);
        mChart.getDescription().setEnabled(false);
        mChart.setMaxVisibleValueCount(60);
        mChart.setPinchZoom(false);
        mChart.setDrawGridBackground(false);

        //xAisFormatter = new DayAxisValueFormatter(mChart);
        xAisFormatter = new SVAxisValueFormatter(mChart);

        XAxis xl = mChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setTypeface(mTfLight);
        xl.setDrawAxisLine(true);
        xl.setDrawGridLines(false);
        xl.setGranularity(1f);
        xl.setLabelCount(25);
        xl.setValueFormatter(xAisFormatter);

        IAxisValueFormatter custom = new MyAxisValueFormatter();

        YAxis yl = mChart.getAxisLeft();
        yl.setTypeface(mTfLight);
        yl.setDrawAxisLine(true);
        yl.setValueFormatter(custom);
        yl.setSpaceTop(15f);
        yl.setDrawGridLines(true);
        yl.setAxisMinimum(0f);

        YAxis yr = mChart.getAxisRight();
        yr.setTypeface(mTfLight);
        yr.setDrawAxisLine(true);
        yr.setDrawGridLines(false);
        yr.setSpaceTop(15f);
        yr.setValueFormatter(custom);
        yr.setAxisMinimum(0f);

        mChart.setFitBars(true);
        mChart.setDescription(null);
        mChart.setNoDataText(getString(R.string.chart_no_data_text));
        //mChart.animateY(2500);

        mChart.getLegend().setEnabled(false);

//        Legend l = mChart.getLegend();
//        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
//        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
//        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
//        l.setDrawInside(false);
//        l.setFormSize(8f);
//        l.setXEntrySpace(4f);

        mChart.invalidate();

        //setData(29, 50);



//        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!isServiceBond) {
            final Intent intent = new Intent(this, NMEAParserService.class);
            isServiceBond = bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        needRefreshData = true;
    }

    @Override
    protected void onPause() {
        super.onPause();

        needRefreshData = false;
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (isServiceBond) {
            unbindService(mServiceConnection);
            isServiceBond = false;
        }
    }

    private void setData(int count, float range) {

        //float barWidth = 9f;
        //float spaceForBar = 10f;
        float start = 1f;

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = (int) start; i < start + count + 1; i++) {
            float mult = (range + 1);
            float val = (float) (Math.random() * mult);

            if (Math.random() * 100 < 25) {
                yVals1.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.star)));
            } else {
                yVals1.add(new BarEntry(i, val));
            }
        }

        BarDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet)mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "CN0");

            set1.setDrawIcons(false);
            //set1.setColors(ColorTemplate.MATERIAL_COLORS);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTypeface(mTfLight);
            //data.setBarWidth(barWidth);
            mChart.setData(data);
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onRMCUpdate(NMEA.GPSPosition position) {

    }

    @Override
    public void onGGAUpdate(NMEA.GPSPosition position) {

    }

    @Override
    public void onAHRSUpdate(NMEA.GPSPosition position) {

    }

    public static final  int[] GROUP_COLORS = {
            ColorTemplate.rgb("#2ecc71"), ColorTemplate.rgb("#f1c40f"), ColorTemplate.rgb("#e74c3c"), ColorTemplate.rgb("#3498db"),
            ColorTemplate.rgb("#9c27b0"), ColorTemplate.rgb("#607d8b")
    };

    @Override
    public void onGSVUpdate(ArrayList<NMEA.SVInfo> svList) {
        if (needRefreshData) {
            ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

            Collections.sort(svList);

            xAisFormatter.setSVList(svList);

            List<Integer> colorList = new ArrayList<>();
            for (int index = 0; index < svList.size(); index++) {
                yVals1.add(new BarEntry(index, svList.get(index).CN0));
                colorList.add(svList.get(index).getColorValue());
            }

            BarDataSet set1;

            if (mChart.getData() != null &&
                    mChart.getData().getDataSetCount() > 0) {
                set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
                set1.setColors(colorList);
                set1.setValues(yVals1);
                mChart.getData().notifyDataChanged();
                mChart.notifyDataSetChanged();
            } else {
                set1 = new BarDataSet(yVals1, "CN0");

                set1.setDrawIcons(false);

                set1.setColors(GROUP_COLORS);

                ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
                dataSets.add(set1);

                BarData data = new BarData(dataSets);
                data.setValueTextSize(10f);
                data.setValueTypeface(mTfLight);
                data.setBarWidth(0.9f);

                mChart.setData(data);
            }

            this.mChart.invalidate();
        }
    }
}
